package com.awspaas.user.apps.cpq.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class CPQ_GetIFAllModuleNumberWeb {

	public String getIFAllModuleNumber(UserContext userContext, String bindId, String cs, String datas) {
		// 将数组转换为列表
				// JSONArray list=JSONObject.parseArray(cs);		
				//JSONArray mList=JSONObject.parseArray(datas);	
				// 获取模块所需参数信息
				Map<String, JSONObject> pMap = new HashMap<String, JSONObject>();
				Map<String, String> nameMap = new HashMap<String, String>();
				Map<String, String> noMap = new HashMap<>();
				List<BO> ps=SDK.getBOAPI().query("BO_EU_CPQ_PROJECT_MSG_PARAMETER_GRIDS").bindId(bindId).list();
				List<BO> bos = SDK.getBOAPI().query("BO_EU_CPQ_PROJECT_MSG_IF").bindId(bindId).list();
				if(ps.size()>0) {
					for (int i = 0; i < ps.size(); i++) {
						BO json = ps.get(i);
						String bh =  json.getString("PARMENTIER_NO");
						String value =  json.getString("PARMENTIER_VALUE");
						String name =json.getString("PARMENTIER_NAME");
						String dw = json.getString("DW");
						JSONObject jsonObject=new JSONObject();
						//判断value是否为数据
						if( NumberUtils.isCreatable(value)) {
							jsonObject.put("type", "1");//值为1者表示value为数值
						}else {
							jsonObject.put("type", "0");//值为0者表示value为字符串
						}
						jsonObject.put("value", value);
						pMap.put(bh, jsonObject);
						nameMap.put(bh, name);
						int num = i + 1;
						noMap.put(bh, "B$" + num);
					}
					System.out.println("pMap:"+pMap.toString());
					
				}

				// 获取模块编码信息
				Map<String, BO> idMap = new HashMap<>();
				String bms = "";
				for (BO json : bos) {
				//	JSONObject json = (JSONObject) string;
					String bm = json.getString("BM");
					if (bms.isEmpty()) {
						bms = "'" + bm + "'";
					} else {
						bms += ",'" + bm + "'";
					}
					String id = json.getString("ID");
					idMap.put(id, json);
				}
				String sql = "select  * from  BO_EU_CPQ_INSTALLATION_FEE where   BM in (" + bms + ")";
				List<RowMap> maps = DBSql.getMaps(sql);
				Map<String, RowMap> moduleMap = new HashMap<>();
				if (maps.size() > 0) {
					for (RowMap rowMap : maps) {
						String mkbm = rowMap.getString("BM");
						moduleMap.put(mkbm, rowMap);
					}
				}
				// 对运输工艺数量进行计算
			   // List<BO> bos = SDK.getBOAPI().query("BO_EU_CPQ_PROJECT_MSG_IF").bindId(bindId).list();
			    //存放已经保存的数据
			  	Map<String, BO> boMap = new HashMap<>();
			  	for (BO bo : bos) {
			  		boMap.put(bo.getString("ID"), bo);
			  	}
			    double totalPrice=0;
			    for (String  id : idMap.keySet()) {
					Workbook workbook = new XSSFWorkbook();
					double price=0;
					try {				
						// 获取对应编码的数据信息；
						if (idMap.containsKey(id)) {
							BO json = idMap.get(id);
							String bm = json.getString("BM");
							// 获取模块维护台账的模块数据
							RowMap rowMap = moduleMap.get(bm);
							String rule = rowMap.getString("JSGS"); // 计算规则
							/**
							 * 计算工艺数量。
							 */
							if (!rule.equals("0") && !rule.isEmpty()) {
								Document document = Jsoup.parse(rule);
								  String newRule=document.text();
								Map<String, BO> materMap = new HashMap<>();
								System.out.println("模块计算规则新："+newRule);
								
								// 设置单元格值
								Sheet sheet = workbook.createSheet("Sheet1");
								for (int i = 0; i < ps.size(); i++) {
									int num = i + 1;
									Cell cellB1 = sheet.createRow(i).createCell(1);
									//JSONObject jsonObject = (JSONObject) list.get(i);
									BO jsonObject = ps.get(i);
									String bh = jsonObject.getString("PARMENTIER_NO");
									JSONObject jsonObject2=	pMap.get(bh);
									String type=jsonObject2.getString("type");
									if(type.equals("0")) {
										cellB1.setCellValue(jsonObject2.getString("value"));
										System.out.println("cellB1:"+cellB1.getStringCellValue());
									}else {
										String value=jsonObject2.getString("value");
										double  numValue=Double.parseDouble(value);		
										 cellB1.setCellValue(numValue);
										 System.out.println("cellB1:"+cellB1.getNumericCellValue());
									}
									
									
								}
								// 获取安装费工艺维护数据中数量计算公式中参数代号，如果有则将代号存放在list中
								for (String key : pMap.keySet()) {
									int num = newRule.indexOf(key);
									if (num > -1) {
										newRule = newRule.replace(key, noMap.get(key));
									}
								}
								// 计算出工艺数量和当前工艺的成本价格
								Cell cellB1 = sheet.createRow(ps.size()+1).createCell(3);
								cellB1.setCellFormula(newRule);
								// 创建公式评估器
								FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
								System.out.println("cellB1value:"+cellB1.getCellFormula());
								formulaEvaluator.evaluateFormulaCell(cellB1);
								// 获取公式计算结果
								CellValue cellValue = formulaEvaluator.evaluate(cellB1);
								System.out.println("The result of the formula is: " + cellValue.getNumberValue());
								double number = cellValue.getNumberValue();
								// 总成本价
								double MKDJ = Double.parseDouble(rowMap.getString("DJ"));// 安装费工艺单价
								double AZXS = Double.parseDouble(json.getString("AZXS").isEmpty()?"0":json.getString("AZXS"));//安装系数
								double MKTotalPrice = number * MKDJ*AZXS;
								price=MKTotalPrice;
								if(boMap.containsKey(id)) {
									BO mbo=	boMap.get(id);
									mbo.set("DJ", MKDJ);// 单价
									mbo.set("SL", number);// 数量
									mbo.set("XTMC", rowMap.getString("SSXT"));// 系统名称
									mbo.set("LX", rowMap.getString("LX"));// 分类
									mbo.set("ZJ", MKTotalPrice);// 总价
									mbo.set("NAME", rowMap.getString("NAME"));// 名称
									mbo.set("DW", rowMap.getString("DW"));// 单位
									mbo.set("BZ", json.getString("BZ"));// 备注
									mbo.set("BM", rowMap.getString("BM"));// 编码
									mbo.set("XTBM", json.getString("XTBM"));// 系统编码
									mbo.set("PX", json.getString("PX"));// 系统序号
									System.out.println("计算后的价格："+mbo.toString());
									SDK.getBOAPI().update("BO_EU_CPQ_PROJECT_MSG_IF", mbo);
								}else {
									BO mbo=	new BO();
									mbo.set("DJ", MKDJ);// 单价
									mbo.set("SL", number);// 数量
									mbo.set("XTMC", rowMap.getString("SSXT"));// 系统名称
									mbo.set("LX", rowMap.getString("LX"));// 分类
									mbo.set("ZJ", MKTotalPrice);// 总价
									mbo.set("NAME", rowMap.getString("NAME"));// 名称
									mbo.set("DW", rowMap.getString("DW"));// 单位
									mbo.set("BZ", json.getString("BZ"));// 备注
									mbo.set("BM", rowMap.getString("BM"));// 编码
									mbo.set("XTBM", json.getString("XTBM"));// 系统编码
									mbo.set("PX", json.getString("PX"));// 系统序号
									SDK.getBOAPI().create("BO_EU_CPQ_PROJECT_MSG_IF", mbo, bindId, userContext.getUID());
								}
								
							}else {
								if(boMap.containsKey(id)) {
									BO mbo=	boMap.get(id);
									mbo.set("DJ", json.getString("DJ"));// 单价
									mbo.set("SL", json.getString("SL"));// 数量
									mbo.set("XTMC", json.getString("XTMC"));// 系统名称
									mbo.set("LX", json.getString("LX"));// 分类
									mbo.set("ZJ", json.getString("ZJ"));// 总价
									double MKDJ = Double.parseDouble(json.getString("ZJ"));// 安装费工艺单价
									price=MKDJ;
									mbo.set("NAME", json.getString("NAME"));// 名称
									mbo.set("DW", json.getString("DW"));// 单位
									mbo.set("BZ", json.getString("BZ"));// 备注
									mbo.set("BM", json.getString("BM"));// 编码
									mbo.set("XTBM", json.getString("XTBM"));// 系统编码
									mbo.set("PX", json.getString("PX"));// 系统序号
									SDK.getBOAPI().update("BO_EU_CPQ_PROJECT_MSG_IF", mbo);			
								}else {
									BO mbo=	new BO();
									mbo.set("DJ", json.getString("DJ"));// 单价
									mbo.set("SL", json.getString("SL"));// 数量
									mbo.set("XTMC", json.getString("XTMC"));// 系统名称
									mbo.set("LX", json.getString("LX"));// 分类
									mbo.set("ZJ", json.getString("ZJ"));// 总价
									double MKDJ = Double.parseDouble(json.getString("ZJ"));// 安装费工艺单价
									price=MKDJ;
									mbo.set("NAME", json.getString("NAME"));// 名称
									mbo.set("DW", json.getString("DW"));// 单位
									mbo.set("BZ", json.getString("BZ"));// 备注
									mbo.set("BM", json.getString("BM"));// 编码
									mbo.set("XTBM", json.getString("XTBM"));// 系统编码
									mbo.set("PX", json.getString("PX"));// 系统序号
									SDK.getBOAPI().create("BO_EU_CPQ_PROJECT_MSG_IF", mbo, bindId, userContext.getUID());				
								}
								
							}
						}
						
					}catch (Exception e){
						 throw  e;
					}finally {
			  			 try {
							workbook.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} 
					
					totalPrice=totalPrice+price;
					
					
			    }
			    //将计算出来的总价格存放到费用明细表中的工程安装费中。
			    BO data=SDK.getBOAPI().query("BO_EU_CPQ_PROJECT_MSG_IFP").addQuery("XH=", "1").detail();
				if(null!=data) {
					data.set("FY", totalPrice);
					SDK.getBOAPI().update("BO_EU_CPQ_PROJECT_MSG_IFP", data);
				}
				ResponseObject ro = ResponseObject.newOkResponse();
				return ro.toString();
	}

}
